<template>
  <div class="previewAndInput">
    <div class="preview" v-show="!inputVisible" @click="showInputAndFocus">
      {{ modelValue }}
    </div>
    <el-input
      v-model="cellValueEdit"
      size="small"
      placeholder="請輸入"
      v-show="inputVisible"
      ref="inputRef"
      @blur="hideInput"
    />
  </div>
</template>

<script setup>
import { ref } from "vue";

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["update:modelValue","updateTotal"]);
const inputVisible = ref(false);
const inputRef = ref(null);
const cellValueEdit = ref(props.modelValue);

const validateInput = (value) => {
  if (value === undefined || value === null || value === "") {
    return false;
  } else if (isNaN(value)) {
    return false;
  } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
    return false;
  } else {
    return true;
  }
};
const showInputAndFocus = () => {
  inputVisible.value = true;
  setTimeout(() => {
    inputRef.value.focus();
  }, 100);
};

const hideInput = () => {
  inputVisible.value = false;
  if (validateInput(cellValueEdit.value)) {
    emit("update:modelValue", cellValueEdit.value);
    emit("updateTotal");
  } else {
    cellValueEdit.value = props.modelValue;
  }
};
</script>

<style scoped lang="scss"></style>
